﻿using Application.CustomerService;
using Domain.Entity.bs;
using Domain.Entity.sys;
using Domain.Entity.zct;
using Domain.Entity;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System.Linq;
using Application.SupplierService;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly ICustomerService customerService;

        public CustomerController(ICustomerService customerService)
        {
            this.customerService = customerService;
        }
        /// <summary>
        /// 查询客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Customer>> GetCustomer(int CurrentPage, string? cust_code, string? cust_name, int? cust_status, string? cust_industry, string? cust_userName)
        {
            FenYe<Customer> fenYe = new FenYe<Customer>()
            {
                CurrentPage = CurrentPage,
            };
            return await customerService.GetCustomer(fenYe, cust_code, cust_name, cust_status, cust_industry, cust_userName);
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="addCustomerDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddCustomer(AddCustomerDto addCustomerDto)
        {
            return await customerService.AddCustomer(addCustomerDto);
        }


        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> DeleteCustomer(int id)
        {
            try
            {
                var result = await customerService.DeleteCustomer(id);

                // 根据 Repository 返回的 int 结果，返回不同的 HTTP 响应
                return result switch
                {
                    1 => Ok(new { code = 1, message = "客户删除成功" }),
                    0 => BadRequest(new { code = 0, message = "删除失败：该客户已被其他单据引用，无法删除" }),
                    -1 => NotFound(new { code = -1, message = "客户不存在或已被删除" }),
                    _ => StatusCode(500, new { code = -2, message = "服务器内部错误：未知的删除结果" })
                };
            }
            catch (System.Exception ex)
            {
                // 记录异常日志 (如果配置了日志系统)
                // _logger.LogError(ex, "删除客户 {SupplierId} 时发生异常", id);
                return StatusCode(500, new { code = -2, message = $"服务器内部错误: {ex.Message}" });
            }
        }


        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="updateCustomerDto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateCustomer(UpdateCustomerDto updateCustomerDto)
        {
            return await customerService.UpdateCustomer(updateCustomerDto);
        }

        /// <summary>
        /// 切换状态
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateStatus(int cust_id, int cust_status)
        {
            
            return await customerService.UpdateStatus(cust_id, cust_status);
        }

        /// <summary>
        /// 查询部门
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Department>> GetDepartment(int? Department_id)
        {
            return await customerService.GetDepartment(Department_id);
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<User>> GetUser(int? Department_id)
        {
            return await customerService.GetUser(Department_id);
        }

        /// <summary>
        /// 查询字典
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<DictData>> GetDictData(int dict_id)
        {
            return await customerService.GetDictData(dict_id);
        }

        /// <summary>
        /// Id查客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Customer> GetIdCustomer(int id)
        {
            return await customerService.GetIdCustomer(id);
        }

        /// <summary>
        /// 高级查询功能
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Task<FenYe<Customer>> GetSeniorCustomer(int CurrentPage, string? cust_code, string? cust_name, string? cust_industry, string? cust_type, string? cust_linkman, string? cust_linkphone, string? cust_email, string? cust_depName, string? cust_userName, int? cust_status, string? cust_address, string? cust_accountName, string? cust_taxpayerNum, string? cust_bankAccount, string? cust_openBank, string? create_name, string? startTime, string? endTime)
        {
            FenYe<Customer> fenYe = new FenYe<Customer>()
            {
                CurrentPage = CurrentPage,
            };
            return customerService.GetSeniorCustomer(fenYe, cust_code, cust_name, cust_industry, cust_type, cust_linkman, cust_linkphone, cust_email, cust_depName, cust_userName, cust_status, cust_address, cust_accountName, cust_taxpayerNum, cust_bankAccount, cust_openBank, create_name, startTime, endTime);
        }

        /// <summary>
        /// 导入客户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportCustomer()
        {
            var file = HttpContext.Request.Form.Files["file"];
            if (file == null || file.Length == 0)
                return BadRequest(new { message = "未上传文件" });

            try
            {
                // 获取现有客户编号 (使用 HashSet 提高查找效率)
                var existingCodesList = await customerService.GetCustomerID(); // 调用客户服务的方法
                var existingCodes = new HashSet<string>(existingCodesList); // 转换为 HashSet

                using var stream = new MemoryStream();
                await file.CopyToAsync(stream);

                using var package = new ExcelPackage(stream);
                var worksheet = package.Workbook.Worksheets[0];

                if (worksheet.Dimension == null)
                    return BadRequest(new { message = "Excel文件没有数据" });

                int rowCount = worksheet.Dimension.Rows;
                int colCount = worksheet.Dimension.Columns;

                // 读取表头
                var headers = Enumerable.Range(1, colCount)
                    .Select(col => worksheet.Cells[1, col].Value?.ToString()?.Trim())
                    .ToList();

                // 验证必要列 (根据你的客户 Excel 格式调整)
                var requiredColumns = new List<string> { "客户编码", "客户" }; // 例如
                var missingColumns = requiredColumns.Where(c => !headers.Contains(c)).ToList();
                if (missingColumns.Any())
                    return BadRequest(new { message = $"Excel缺少必要列: {string.Join(", ", missingColumns)}" });

                var successCount = 0;
                var errorMessages = new List<string>();

                // 从第二行开始读取数据
                for (int row = 2; row <= rowCount; row++)
                {
                    // 假设你有一个 AddCustomerDto 类
                    var customerDto = new AddCustomerDto();
                    bool hasError = false;

                    for (int col = 1; col <= colCount; col++)
                    {
                        var header = headers[col - 1];
                        var value = worksheet.Cells[row, col].Value?.ToString()?.Trim();

                        try
                        {
                            switch (header)
                            {
                                case "客户编码":
                                    customerDto.cust_code = value;
                                    break;
                                case "客户":
                                    customerDto.cust_name = value;
                                    break;
                                case "所属行业":
                                    customerDto.cust_industry = value;
                                    break;
                                case "客户来源":
                                    customerDto.cust_source = value;
                                    break;
                                case "联系人":
                                    customerDto.cust_linkman = value;
                                    break;
                                case "联系电话":
                                    customerDto.cust_linkphone = value;
                                    break;
                                case "电子邮箱":
                                    customerDto.cust_email = value;
                                    break;
                                case "销售部门":
                                    customerDto.cust_depName = value;
                                    break;
                                case "销售负责人":
                                    customerDto.cust_userName = value;
                                    break;
                                case "客户地址":
                                    customerDto.cust_address = value;
                                    break;
                                case "备注":
                                    customerDto.remark = value;
                                    break;
                                case "账户名称":
                                    customerDto.cust_accountName = value;
                                    break;
                                case "纳税人识别号":
                                    customerDto.cust_taxpayerNum = value;
                                    break;
                                case "银行账户":
                                    customerDto.cust_bankAccount = value;
                                    break;
                                case "开户银行":
                                    customerDto.cust_openBank = value;
                                    break;
                                case "开户行地址":
                                    customerDto.cust_openBankAddress = value;
                                    break;
                                case "创建人":
                                    customerDto.create_name = value;
                                    break;
                                case "创建时间":
                                    customerDto.create_time = value;
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            errorMessages.Add($"第{row}行[{header}]列处理错误: {ex.Message}");
                            hasError = true;
                            break;
                        }
                    }

                    // 跳过错误行
                    if (hasError) continue;

                    // 验证必要字段 (根据你的 DTO 调整)
                    if (string.IsNullOrEmpty(customerDto.cust_code))
                    {
                        errorMessages.Add($"第{row}行错误: 客户编码不能为空");
                        continue;
                    }

                    // 检查重复 (使用 HashSet.Contains，效率高)
                    if (existingCodes.Contains(customerDto.cust_code))
                    {
                        errorMessages.Add($"第{row}行错误: 客户编码 {customerDto.cust_code} 已存在");
                        continue;
                    }

                    // 添加客户
                    var result = await customerService.AddCustomer(customerDto); // 调用客户服务的添加方法
                    if (result == 1) // 假设 1 表示成功
                    {
                        successCount++;
                        // 更新内存中的 HashSet，防止后续行导入相同编码导致重复
                        existingCodes.Add(customerDto.cust_code);
                    }
                    else
                    {
                        errorMessages.Add($"第{row}行导入失败: 服务返回错误代码 {result}");
                    }
                }

                return Ok(new
                {
                    successCount,
                    errorCount = errorMessages.Count,
                    errors = errorMessages
                });
            }
            catch (Exception ex)
            {
                // 记录日志
                return StatusCode(500, new { message = "处理文件时出错", error = ex.Message, stackTrace = ex.StackTrace });
            }
        }



        /// <summary>
        /// 查询所有客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Customer>> GetCustomers()
        {
            return await customerService.GetCustomers();
        }
    }
}
